<?php

/*
 * Copyright (C) 2009 - 2011 Pham Cong Dinh
 *
 * This file is part of Spica.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 3 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

/**
 * Provides a set of methods to create a hash on a password or generate random string
 * that can be used as passwords.
 *
 * This class is slightly modified from Portable PHP password hashing framework,
 * written by Solar Designer <solar at openwall.com> in 2004-2006 and placed in
 * the public domain. (Version 0.1).
 *
 * namespace spica\core\utils\PortableHashUtils
 *
 * @category   spica
 * @package    core
 * @subpackage utils
 * @author     Pham Cong Dinh <pcdinh at phpvietnam dot net>
 * @since      Version 0.3
 * @since      April 03, 2009
 * @link       http://www.openwall.com/phpass/
 * @version    $Id: HashUtils.php 1869 2011-01-07 18:55:25Z pcdinh $
 */
class SpicaPortableHashUtils
{
    /**
     * Creates a hash string for a string (like a password).
     *
     * @param string $password
     */
    public static function createHash($password)
    {
        $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

        $randomState = self::uniqueId();
        $random      = '';
        $count       = 6;
        $random      = md5(uniqid(mt_rand(), true));

        if (strlen($random) < $count)
        {
            $random = '';

            for ($i = 0; $i < $count; $i += 16)
            {
                $randomState = md5(self::uniqueId() . $randomState);
                $random     .= pack('H*', md5($randomState));
            }

            $random = substr($random, 0, $count);
        }

        $hash = self::_encrypt($password, self::_generateSalt($random, $itoa64), $itoa64);

        if (strlen($hash) == 34)
        {
            return $hash;
        }

        return md5($password);
    }

    /**
     * Checks for correct password
     */
    public static function checkHash($password, $hash)
    {
        $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        
        if (strlen($hash) == 34)
        {
            return (self::_encrypt($password, $hash, $itoa64) === $hash) ? true : false;
        }

        return (md5($password) === $hash) ? true : false;
    }

    /**
     * Generates salt for hash generation
     */
    protected static function _generateSalt($input, &$itoa64, $iterationCount = 6)
    {
        if ($iterationCount < 4 || $iterationCount > 31)
        {
            $iterationCount = 8;
        }

        $output  = '$S$';
        $output .= $itoa64[min($iterationCount + ((PHP_VERSION >= 5) ? 5 : 3), 30)];
        $output .= self::_encode64($input, 6, $itoa64);

        return $output;
    }

    /**
     * Encodes hash.
     *
     * @param  string $input
     * @param  int $count
     * @param  array $itoa64
     * @return string
     */
    protected static function _encode64($input, $count, &$itoa64)
    {
        $output = '';
        $i = 0;

        do
        {
            $value   = ord($input[$i++]);
            $output .= $itoa64[$value & 0x3f];

            if ($i < $count)
            {
                $value |= ord($input[$i]) << 8;
            }

            $output .= $itoa64[($value >> 6) & 0x3f];

            if ($i++ >= $count)
            {
                break;
            }

            if ($i < $count)
            {
                $value |= ord($input[$i]) << 16;
            }

            $output .= $itoa64[($value >> 12) & 0x3f];

            if ($i++ >= $count)
            {
                break;
            }

            $output .= $itoa64[($value >> 18) & 0x3f];
        } while ($i < $count);

        return $output;
    }

    /**
     * Encrypts a string.
     *
     * @param  string $password
     * @param  string $setting
     * @param  array $itoa64
     * @return string
     */
    protected static function _encrypt($password, $setting, &$itoa64)
    {
        $output = '*';

        // Check for correct hash
        if (substr($setting, 0, 3) != '$S$')
        {
            return $output;
        }

        $countLog2 = strpos($itoa64, $setting[3]);

        if ($countLog2 < 7 || $countLog2 > 30)
        {
            return $output;
        }

        $count = 1 << $countLog2;
        $salt  = substr($setting, 4, 8);

        if (strlen($salt) != 8)
        {
            return $output;
        }

        $hash = md5($salt.$password, true);
        do
        {
            $hash = md5($hash.$password, true);
        } while (--$count);

        $output  = substr($setting, 0, 12);
        $output .= self::_encode64($hash, 16, $itoa64);
        return $output;
    }

    /**
     * Creates an unique ID.
     *
     * @return string
     */
    public static function uniqueId()
    {
        return uniqid(microtime(), 1);
    }

    /**
     * Generates a random password.
     *
     * @param  int  $length  The length of the password
     * @param  bool $special Chars Special characters should be used in the generated password or not.
     * @return string
     */
    public static function randString($length = 12, $specialChars = true)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

        if (true === $specialChars)
        {
            $chars .= '!@#$%^&*()';
        }

        $password = '';

        for ($i = 0; $i < $length; $i++)
        {
            $password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }

        return $password;
    }
}

?>